<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

namespace ApplicationsModule\GalleryModule;

use Nette\Environment;
use \dibi;

use WebtopModule\BasePresenter;
use ApplicationsModule\GalleryModule\PicasaTokenNotReachableException;
use ApplicationsModule\GalleryModule\PicasaWeb;
/**
 * Description of PicasaAuthenticatorPresenter
 *
 * @author honza
 */
class PicasaAuthenticatorPresenter extends BasePresenter {
    
    private $callbackUri;
    
    public function startup() {
        $this->callbackUri = $this->setCallbackUrl();
        parent::startup();
        header ( "Content-type:text/html; charset=utf-8" ); // TODO: poresit
        if ($this->isAjax()) {
	    $this->invalidateControl("celebriogalleryappSnippet");
	}

	if(!Environment::getUser()->isLoggedIn()) {
            throw new \Exception("User is not authenticated");
	    return;
        }
    }
    
    public function actionDefault() {
        $credentials = PicasaWeb::getConnectionSettings();
        $client_id = $credentials["client_id"];
        $redirectUri = $this->callbackUri;
        $this->redirectUri('https://accounts.google.com/o/oauth2/auth?client_id='. $client_id .'&redirect_uri=' . $redirectUri . '&scope=https://picasaweb.google.com/data/&response_type=code');
    }
    
    public function renderAccessTokenGetter() {
        $code = $this->getHttpRequest()->getQuery("code");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        
        $credent = PicasaWeb::getConnectionSettings();
        $options = array(
            "code" => $code,
            "client_id" => $credent["client_id"],
            "client_secret" => $credent["client_secret"],
            "redirect_uri" => $this->callbackUri,
            "grant_type" => "authorization_code"
        );
        curl_setopt($curl, CURLOPT_POSTFIELDS, $options);
        $response_json = curl_exec($curl);
        curl_close($curl);
        if($this->getHttpRequest()->getQuery("error") === "access_denied") {
            $this->redirect("AccessDenied");
        }
        $json = json_decode($response_json);
        $picasaDriver = new PicasaWeb();
        $picasaDriver->setUser($this->getUser());
        $picasaDriver->saveToken($json->refresh_token);
        $this->redirect("Default:default");
    }
    
    public function actionParseAccessToken() {
        $access_token = $this->getHttpRequest()->getQuery("access_token");
        if($access_token === null) {
            $this->redirect("Default:PicasaNotAvailable");
        }
        $this->getSession("picasa")->token = $access_token;
        $this->getSession("picasa")->setExpiration(3000);
        
        $this->redirect("Default:default");
        return $access_token;
    }
    
    public function renderAccessDenied() {
        $this->template->error = _("Access was not granted");
    }
    
    private function setCallbackUrl() {
        $requestUri = $this->getHttpRequest()->uri;
        $uriPath = $requestUri->scriptPath;
        $host = $requestUri->host;
        $redirectUri = "http://" . $host . $uriPath . "app/picasaAuthenticator/accessTokenGetter";
        return $redirectUri;
    }
}